package com.siwei.mes.service.experiment.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.experiment.ExperimentSampleSmoke;
import com.siwei.mes.entity.experiment.ExperimentSampleTestProject;
import com.siwei.mes.entity.experiment.concrete.KsdjSmoke;
import com.siwei.mes.entity.experiment.concrete.UpdateKsdjSmoke;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.experiment.ExperimentSampleSmokeMapper;
import com.siwei.mes.mapper.experiment.ExperimentSampleTestProjectMapper;
import com.siwei.mes.service.system.AuthService;
import com.siwei.mes.service.experiment.ExperimentSampleSmokeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 试验台账抽样(ExperimentSampleSmoke)表服务实现类
 *
 * @author linzi
 * @since 2023-12-28 20:47:31
 */
@Service
public class ExperimentSampleSmokeServiceImpl implements ExperimentSampleSmokeService {
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private AuthService authService;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentSampleTestProjectMapper experimentSampleTestProjectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ExperimentSampleSmoke entity) {
        assertTrue(experimentMapper.loadById(entity.getExperimentId()) == null, "试验台账信息不存在");
        entity.setSamplePersonId(authService.getLoginUserId());
        entity.setSamplePersonName(authService.getLoginUserName());
        entity.setSampleTime(new Date());
        entity.init(true);
        /**如果对应抽样试验项目不为空 查询出对应的JSON数据*/
        if (StringUtils.isNotBlank(entity.getSampleTestProjectCode())) {
            ExperimentSampleTestProject testProject = experimentSampleTestProjectMapper.selectByItemCode(entity.getSampleTestProjectCode());
            if (testProject != null) {
                entity.setSampleTestProjectName(testProject.getTestName());
                // JSONArray testProjectJsonArray = ExperimentSampleTestProject.payloadJsonArray(testProject.getGenJson(),testProject.getGenNumber());
                // entity.setSampleTestProjectJson(testProjectJsonArray);
                entity.setTestProjectCode(testProject.getTestCode());
                entity.setTestProjectName(testProject.getTestName());
                entity.setFreqNumber(testProject.getFreqNumber());
                entity.setFreqUnit(testProject.getFreqUnit());
            }
        }
        experimentSampleSmokeMapper.insertSelective(entity);
        return entity.getId();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ExperimentSampleSmoke entity) {
        assertTrue(experimentMapper.loadById(entity.getExperimentId()) == null, "试验台账信息不存在");
        ExperimentSampleSmoke experimentSampleSmoke = experimentSampleSmokeMapper.selectByPrimaryKey(entity.getId());
        assertTrue(experimentSampleSmoke == null, "试验台账抽样信息不存在");
        entity.init(false);
        experimentSampleSmokeMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        ExperimentSampleSmoke experimentSampleSmoke = experimentSampleSmokeMapper.selectByPrimaryKey(id);
        assertTrue(experimentSampleSmoke == null, "试验台账抽样信息不存在");
        experimentSampleSmokeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<ExperimentSampleSmoke> getPage(PageQuery<ExperimentSampleSmoke, ExperimentSampleSmoke> query) {
        ExperimentSampleSmoke searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> experimentSampleSmokeMapper.getList(searchParam));
    }

    @Override
    public ExperimentSampleSmoke loadById(Long id) {
        return experimentSampleSmokeMapper.loadById(id);
    }

    @Override
    public List<ExperimentSampleSmoke> getAll(ExperimentSampleSmoke entity) {
        return experimentSampleSmokeMapper.getList(entity);
    }

    @Override
    public List<KsdjSmoke> getKsDetail(Long experimentId) {
        TreeMap<String, KsdjSmoke> ksdjSmokeMap = new TreeMap<>();
        try {
            ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke().setIsTestBlock(1)
                    .setExperimentId(experimentId).setTestProjectCode("CONCRETE_PARAM_KSDJ");
            List<ExperimentSampleSmoke> smokeList = experimentSampleSmokeMapper.getList(sampleSmoke);
            if (smokeList.isEmpty()) {
                assertTrue("该试验台账没有抗渗等级相关记录");
            }
            JSONArray lastJson = new JSONArray();
            /**获取最长的一个JSONArray 的json数据*/
            for (ExperimentSampleSmoke entity : smokeList) {
                JSONArray sampleTestProjectJson = entity.getSampleTestProjectJson();
                if (lastJson.isEmpty()) {
                    lastJson = sampleTestProjectJson;
                } else {
                    int lastJsonSize = lastJson.size();
                    int size = sampleTestProjectJson.size();
                    if (size > lastJsonSize) {
                        lastJson = sampleTestProjectJson;
                    }
                }
            }
            /**排序*/
            lastJson.sort(Comparator.comparing(obj -> ((JSONObject) obj).getBigDecimal("syyl")));
            /**先丢到map里面去*/
            for (Object o : lastJson) {
                JSONObject object = (JSONObject) o;
                KsdjSmoke ksdjSmoke = new KsdjSmoke();
                ksdjSmoke.setExperimentId(experimentId);
                ksdjSmoke.setSyyl(object.getString("syyl"));
                ksdjSmoke.setJysj(object.getString("jysj"));
                ksdjSmoke.setSfssList(new ArrayList<>());
                ksdjSmokeMap.put(ksdjSmoke.getSyyl(), ksdjSmoke);
            }
            /**遍历抗渗抽样记录组装记录*/
            for (ExperimentSampleSmoke entity : smokeList) {
                JSONArray projectJson = entity.getSampleTestProjectJson();
                for (Object o : projectJson) {
                    JSONObject object = (JSONObject) o;
                    if (object.get("sfss") == null) {
                        continue;
                    }
                    if (ksdjSmokeMap.containsKey(object.getString("syyl"))) {
                        KsdjSmoke ksdjSmoke = ksdjSmokeMap.get(object.getString("syyl"));
                        List<Map<String, Object>> sfssList = ksdjSmoke.getSfssList();
                        if (sfssList.isEmpty()) {
                            sfssList = new ArrayList<>();
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put(entity.getSmokeNo(), object.getString("sfss"));
                        sfssList.add(map);
                        ksdjSmoke.setSfssList(sfssList);
                        ksdjSmokeMap.put(object.getString("syyl"), ksdjSmoke);
                    }
                }
            }
        } catch (Exception e) {
            assertTrue("查询对应试验台账的抗渗记录失败" + e.getMessage());
        }
        return new ArrayList<>(ksdjSmokeMap.values());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateKsDetail(UpdateKsdjSmoke updateKsdjSmoke) {
        /**key:试验台账id value:试验台账抽样信息*/
        Map<String, ExperimentSampleSmoke> smokeMap = new HashMap<>();
        /**查询对应的抽样记录信息*/
        Long experimentId = updateKsdjSmoke.getExperimentId();
        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke().setIsTestBlock(1)
                .setExperimentId(experimentId).setTestProjectCode("CONCRETE_PARAM_KSDJ");
        List<ExperimentSampleSmoke> smokeList = experimentSampleSmokeMapper.getList(sampleSmoke);
        if (smokeList.isEmpty()) {
            assertTrue("该试验台账没有抗渗等级相关记录");
        }

        for (ExperimentSampleSmoke smoke : smokeList) {
            /**这里默认直接变成空的  后面组装在新增进来*/
            smoke.setSampleTestProjectJson(new JSONArray());
            smokeMap.put(smoke.getSmokeNo(), smoke);
        }

        List<KsdjSmoke> ksdjSmokeList = updateKsdjSmoke.getKsdjSmokeList();
        for (KsdjSmoke ksdjSmoke : ksdjSmokeList) {
            List<Map<String, Object>> sfssList = ksdjSmoke.getSfssList();
            for (Map<String, Object> map : sfssList) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String smokeNo = entry.getKey();// 抽样记录id
                    Object sfss = entry.getValue();// 是否渗水

                    if (smokeMap.containsKey(smokeNo)) {
                        ExperimentSampleSmoke entity = smokeMap.get(smokeNo);
                        JSONArray projectJson = entity.getSampleTestProjectJson();
                        /**这里直接添加进去*/
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("syyl", ksdjSmoke.getSyyl());
                        jsonObject.put("jysj", ksdjSmoke.getJysj());
                        jsonObject.put("sfss", sfss);
                        projectJson.add(jsonObject);

                        entity.setSampleTestProjectJson(projectJson);
                        smokeMap.put(smokeNo, entity);
                    }
                }
            }
        }

        for (ExperimentSampleSmoke smoke : smokeMap.values()) {
            smoke.init(false);
            experimentSampleSmokeMapper.updateByPrimaryKeySelective(smoke);
        }
    }
}
